package service

import (
	"strconv"
	"time"

	"gitee.com/daigd/v-blog-demo-go/config"
	"gitee.com/daigd/v-blog-demo-go/model"
)

// Save 创建一篇文章
func Save(article *model.Article) (err error) {
	result, err := config.DB.Exec("insert into v_article(article_name,content,author,created_at,created_by) values (?,?,?,?,?)", article.ArticleName, article.Content, article.Author, time.Now(), article.CreatedBy)
	if err != nil {
		return
	}
	insertID, _ := result.LastInsertId()
	id, err := strconv.Atoi(strconv.FormatInt(insertID, 10))
	if err != nil {
		article.ArticleID = id
	}
	return
}

//QueryArticleByID 根据文章Id查询文章记录
func QueryArticleByID(id int) (article *model.Article, err error) {
	article = &model.Article{}
	err = config.DB.QueryRow("select article_name,content,author,created_at,created_by from v_article where id = ?", id).Scan(article.ArticleName, article.Content, article.Author, article.CreatedAt, article.CreatedBy)
	return article, err
}

// ListArticle 获取文章列表
func ListArticle() (articles []model.Article, err error) {
	rows, err := config.DB.Query("select article_id,article_name,content,author,created_at,created_by from v_article where 1=1 ")
	if err != nil {
		return
	}
	articles = make([]model.Article, 0)
	for rows.Next() {
		article := model.Article{}
		err = rows.Scan(&article.ArticleID, &article.ArticleName, &article.Content, &article.Author, &article.CreatedAt, &article.CreatedBy)
		if err != nil {
			return
		}
		articles = append(articles, article)
	}
	return articles, err
}
